package da.asclass.login
{
    import da.asclass.events.cl.LoginEvent;

    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.net.SharedObject;

    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.rpc.remoting.RemoteObject;

    public class RemoteLogin extends EventDispatcher
    {
        private var myShare:SharedObject = null;
        private var userName:String = null;
        private var password:String = null;
        private var remoteLogin:RemoteObject = null;
        private var le:LoginEvent = null;
        public static const LOGIN_SUCCESS:String = "LOGIN_SUCCESS";
        public static const LOGIM_FAILED:String = "LOGIM_FAILED";
        public static const REMOTE_CALL_FAILED:String = "REMOTE_CALL_FAILED";

        public function RemoteLogin ( txtUserName:String = null , txtPassword:String = null )
        {
            this.userName = txtUserName;
            this.password = txtPassword;
            remoteLogin = new RemoteObject( "Login" );
            remoteLogin.addEventListener( ResultEvent.RESULT , loginRE );
            remoteLogin.addEventListener( FaultEvent.FAULT , loginFE );
            le = new LoginEvent();
        }

        public function login ():void
        {
            remoteLogin.login( this.userName , this.password );
        }

        public function loginRE ( event:ResultEvent ):void
        {
            switch ( event.result )
            {
                case 1:
                    le.resultType = RemoteLogin.LOGIN_SUCCESS;
                    this.myShare = SharedObject.getLocal( "daim.sharedObject" );
                    this.myShare.data.userName = this.userName;
                    this.myShare.flush();
                    break;
                case 2:
                    le.resultType = RemoteLogin.LOGIM_FAILED;
                    break;
                default:
                    le.resultType = RemoteLogin.REMOTE_CALL_FAILED;
                    break;
            }
            this.dispatchEvent( le );
        }

        public function loginFE ( event:FaultEvent ):void
        {
            le.resultType = RemoteLogin.REMOTE_CALL_FAILED;
            this.dispatchEvent( le );
        }
    }
}